package club.monkeywood.course.service.thrift;

import club.monkeywood.thrift.user.IUserService;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
public class UserServiceProvider {

    @Value("${thrift.user.ip}")
    private String serverIp;

    @Value("${thrift.user.port}")
    private int serverPort;

    @Bean
    public IUserService.Client getUserService() {
        System.out.println("进入getUserService");
        System.out.println("serverIp=" + serverIp);
        System.out.println("serverPort=" + serverPort);
        return getService(serverIp, serverPort);
    }

    public <T> T getService(String ip, int port) {
        TSocket socket = new TSocket(ip, port, 30000);
        TTransport transport = new TFramedTransport(socket);
        try {
            transport.open();
        } catch (TTransportException e) {
            e.printStackTrace();
            return null;
        }
        TProtocol protocol = new TBinaryProtocol(transport);

        TServiceClient result = null;

        //修改类类型
        result = new IUserService.Client(protocol);

        return (T)result;
    }

}
